define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue', 'CustomFormatter','Hook', 'image'], function ($, undefined, Backend, Table, Form,Vue,Formatter,Hook,Image) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'goods/index' + location.search,
                    add_url: 'goods/add',
                    edit_url: 'goods/edit',
                    del_url: 'goods/del',
                    multi_url: 'goods/multi',
                    table: 'goods',
                }
            });
            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Goods_id')},
                        {field: 'name', title: __('Goods_name'),operate:"LIKE",formatter : function(value, row, index, field){

                                return ""+value+"";
                            },
                            cellStyle : function(value, row, index, field){
                                return {
                                    css: {"min-width": "150px",
                                        "white-space": "nowrap",
                                        "text-overflow": "ellipsis",
                                        "overflow": "hidden",
                                        "max-width":"300px"
                                    }
                                };
                            }},
                        {field: 'category1.name', title: __('Category_id1'),operate:"LIKE"},
                        {field: 'category2.name', title: __('Category_id2'),operate:"LIKE"},
                        {field: 'goods_price', title: __('Goods_price'), operate:'BETWEEN'},
                        {field: 'sold_number', title: __('已售数量'), operate:'BETWEEN'},
                        {field: 'thumbnail_image', operate:false ,title: __('Thumbnail_image'), events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'goods_images', operate:false ,title: __('Goods_images'), events: Table.api.events.image, formatter: Table.api.formatter.images},
                        {field: 'qrwechatcode', operate:false ,title: __('小程序码'), events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'qrcode', operate:false ,title: __('商品二维码'), events: Table.api.events.image, formatter: Table.api.formatter.image},
                        {field: 'status', title: __('Status'), searchList: {"1":__('Status 1'),"2":__('Status 2')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate,
                            buttons: [
                                {
                                    name: 'edit',
                                    icon: 'fa fa-pencil',
                                    title: __('Edit'),
                                    extend: 'data-toggle="tooltip" data-area=\'["100%", "100%"]\'',
                                    classname: 'btn btn-xs btn-success btn-editone',
                                    url: $.fn.bootstrapTable.defaults.extend.edit_url
                                }
                            ],
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        attrGroups: [],
                        attrItems: [],
                        productSkus: [],
                        skus: [],
                        url:'http://image.intlsgp.com/'
                    }
                },
                computed: {
                    productSkusStr() {
                        return JSON.stringify(this.productSkus)
                    }
                },
                mounted() {
                    Image.init()
                },
                methods: {
                    setAttrGroupName(i, e) {
                        this.$set(this.attrGroups, i, e.target.value)
                    },
                    addRow() {
                        var val = this.$refs['attr-group-name'].value
                        if ($.trim(val) == '') {
                            Toastr.error("不能为空")
                            return
                        }
                        if (val.indexOf(',') > -1) {
                            Toastr.error("规格子项 " + val + " 不能包含符号‘,’")
                            return
                        }
                        this.attrGroups.push(val)
                        this.$refs['attr-group-name'].value = ''
                    },
                    addChild(index) {
                        var val = this.$refs['attr-item-name-' + index][0].value
                        if ($.trim(val) == '') {
                            Toastr.error("不能为空")
                            return
                        }
                        if (val.indexOf(',') > -1) {
                            Toastr.error("规格 " + val + " 不能包含符号‘,’")
                            return
                        }
                        if (!val) return false
                        if (this.attrItems[index]) {
                            this.attrItems[index].push(val)
                        } else {
                            this.attrItems.push([val])
                        }
                        this.$refs['attr-item-name-' + index][0].value = ""
                        this.generateProducts()

                    },
                    upimage(i) {
                        Image.open(function(data) {
                            $('#c-attr-image-' + i).val(data.url)
                            if (vm.skus[i]) {
                                vm.$set(vm.skus[i], 'image', data.url)
                            } else {
                                vm.$set(vm.skus, i, {image: data.url})
                            }
                            Image.close()
                        })
                    },
                    removeChild(i, j) {
                        this.attrItems[i].splice(j, 1);
                        this.generateProducts();
                    },
                    removeGroup(i) {
                        //  console.log(this.attrGroups);
                        this.attrGroups.splice(i, 1);

                        // this.attrGroups.pop(i);
                        // if (this.attrItems[i])
                        //     this.attrItems.pop(i);
                        this.generateProducts();
                    },
                    generateProducts() {
                        this.productSkus = this.descartes(this.attrItems)
                        this.generateSkus();
                    },
                    generateSkus() {
                        var skus = [];
                        for(var i = 0; i < this.productSkus.length; i ++) {
                            var item = this.productSkus[i];
                            var index = Controller.api.find_rows(this.skus, {value: item.join(',')});
                            if (index == -1) skus.push({
                                value: item.join(','), market_price: '', price: '', stock: '', image: ''
                            })
                            else skus.push(this.skus[index]);
                        }
                        this.$set(this, 'skus', skus);
                    },
                    descartes(array){
                        if (array.length == 0) return []
                        if( array.length < 2 ) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat( Array.isArray(c) ? c : [c] );
                                    t.push(s);
                                    res.push(t);
                                })});
                            return res;
                        });
                    }
                }
            })
            Controller.api.bindevent();
            window.batchSetAttrs = function(field) {
                $('.attr-' + field).val($('#batch-' + field).val())
            }
            Hook.listen('document')
            $("#c-category2_id").data("params",function () {
                return {custom:{pid:$("#c-category_id").val()}}
            })
        },
        edit: function () {
            Controller.api.bindevent();
            var vm = new Vue({
                el: '#app',
                data() {
                    return {
                        attrGroups: [],
                        attrItems: [],
                        productSkus: [],
                        skus: [],
                        url:'http://image.intlsgp.com/'
                    }
                },
                computed: {
                    productSkusStr() {
                        return JSON.stringify(this.productSkus)
                    }
                },



                mounted() {
                    skus = skus
                    if (skus.length) {
                        this.skus = skus
                        this.attrGroups = this.skus[0].keys.split(',')
                        this.attrItems = attrItems;
                        this.generateProducts()
                    }
                    Image.init()
                },
                methods: {
                    setAttrGroupName(i, e) {
                        this.$set(this.attrGroups, i, e.target.value)
                    },
                    addRow() {
                        var val = this.$refs['attr-group-name'].value
                        if ($.trim(val) == '') {
                            Toastr.error("不能为空")
                            return
                        }
                        if (val.indexOf(',') > -1) {
                            Toastr.error("规格 " + val + " 不能包含符号‘,’")
                            return
                        }
                        this.attrGroups.push(val)
                        this.$refs['attr-group-name'].value = ''
                    },
                    addChild(index) {
                        var val = this.$refs['attr-item-name-' + index][0].value
                        if ($.trim(val) == '') {
                            Toastr.error("不能为空")
                            return
                        }
                        if (val.indexOf(',') > -1) {
                            Toastr.error("规格子项 " + val + " 不能包含符号‘,’")
                            return
                        }
                        if (!val) return false
                        if (this.attrItems[index]) {
                            this.attrItems[index].push(val)
                        } else {
                            this.attrItems.push([val])
                        }
                        this.$refs['attr-item-name-' + index][0].value = ""
                        this.generateProducts()
                    },
                    upimage(i) {
                        Image.open(function(data) {
                            console.log(vm.skus, i)
                            if (vm.skus[i]) {
                                vm.$set(vm.skus[i], 'image', data.url)
                            } else {
                                vm.$set(vm.skus, i, {image: data.url})
                            }
                            Image.close()
                        })
                    },

                    removeChild(i, j) {
                        this.attrItems[i].splice(j, 1)
                        this.generateProducts()
                    },
                    removeGroup(i) {
                        this.attrGroups.splice(i, 1);
                        this.attrItems.pop(i)
                        this.generateProducts()
                    },
                    batchSetAttr($type) {
                        for(var i = 0; i < this.skus.length; i ++) {
                            this.$set(this.skus[i], $type, this.$refs['input-' + $type].value)
                        }
                    },
                    generateProducts() {
                        this.productSkus = this.descartes(this.attrItems)
                        this.generateSkus()
                    },
                    generateSkus() {
                        var skus = [];
                        for(var i = 0; i < this.productSkus.length; i ++) {
                            var item = this.productSkus[i];
                            var index = Controller.api.find_rows(this.skus, {value: item.join(',')});
                            if (index == -1) skus.push({
                                value: item.join(','), market_price: '', price: '', stock: '', image: ''
                            })
                            else skus.push(this.skus[index]);
                        }
                        this.$set(this, 'skus', skus);
                    },
                    descartes(array){
                        if (array.length == 0) return []
                        if( array.length < 2 ) {
                            var res = []
                            array[0].forEach(function(v) {
                                res.push([v])
                            })
                            return res
                        }
                        return [].reduce.call(array, function(col, set) {
                            var res = [];
                            col.forEach(function(c) {
                                set.forEach(function(s) {
                                    var t = [].concat( Array.isArray(c) ? c : [c] );
                                    t.push(s);
                                    res.push(t);
                                })});
                            return res;
                        });
                    }

                }
            })
            window.batchSetAttr = function(field) {
                $('.attr-' + field).val($('#batch-' + field).val())
            }
            Hook.listen('form')
            $("#c-category2_id").data("params",function () {
                return {custom:{type:'goods',pid:$("#c-category_id").val(),is_true:1}}
            })
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            find_rows(rows, filter, return_index = true) {
                for (let i = 0; i < rows.length; i ++) {
                    let res = true
                    let item = rows[i]
                    for (let key in filter) {
                        if (item[key] != filter[key]) res = false
                    }
                    if (res) return return_index ? i : item
                }
                return return_index ? -1 : null
            },
        }
    };
    return Controller;
});